using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using User.Service;
using hao_Dto.User;
using hao_Common.Response.Extensions;
using hao_Common.Response.Models;
using hao_Common.Response.Builders;
using hao_Common.Consul.Services; // 添加Consul服务发现引用
using hao_Common.Logging.Helpers;
using System.Text.Json;

namespace hao_User.Api.Controllers
{
    [ApiController]
    [Route("api/user")]
    public class UserController : ControllerBase
    {
        private readonly IUserService _userService;
        private readonly IServiceDiscovery _serviceDiscovery; // 注入服务发现接口
        private readonly HttpClient _httpClient; // 注入HttpClient
        private readonly ILogger<UserController> _logger; // 注入日志

        public UserController(
            IUserService userService,
            IServiceDiscovery serviceDiscovery,
            HttpClient httpClient,
            ILogger<UserController> logger)
        {
            _userService = userService;
            _serviceDiscovery = serviceDiscovery;
            _httpClient = httpClient;
            _logger = logger;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        [HttpPost("login")]
        public async Task<IActionResult> Login([FromBody] LoginDto loginDto)
        {
            var ipAddress = HttpContext.Connection.RemoteIpAddress?.ToString();
            var userAgent = Request.Headers["User-Agent"].ToString();
            
            // 记录登录尝试
            _logger.LogUserAction("Anonymous", "登录尝试", new { 
                UserName = loginDto.UserName, 
                IpAddress = ipAddress,
                UserAgent = userAgent 
            }, ipAddress);
            
            try
            {
                var result = await _userService.LoginAsync(loginDto);
                
                if (result != null)
                {
                    // 记录登录成功
                    _logger.LogUserAction(result.User.Id.ToString(), "登录成功", new { 
                        UserName = result.User.UserName,
                        LoginTime = DateTime.UtcNow,
                        IpAddress = ipAddress,
                        UserAgent = userAgent
                    }, ipAddress);
                    
                    _logger.LogSecurity("用户登录成功", result.User.Id.ToString(), ipAddress, new {
                        UserName = result.User.UserName,
                        LoginMethod = "Password"
                    });
                    
                    return this.SuccessResult(result, "登录成功");
                }
                else
                {
                    // 记录登录失败
                    _logger.LogSecurity("登录失败-用户名或密码错误", null, ipAddress, new {
                        UserName = loginDto.UserName,
                        Reason = "InvalidCredentials"
                    });
                    
                    return this.UnauthorizedResult("用户名或密码错误");
                }
            }
            catch (Exception ex)
            {
                // 记录登录异常
                _logger.LogErrorWithContext(ex, "用户登录异常", new {
                    UserName = loginDto.UserName,
                    IpAddress = ipAddress,
                    UserAgent = userAgent
                });
                
                return this.ServerErrorResult($"登录失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        [HttpPost("register")]
        public async Task<IActionResult> Register([FromBody] RegisterDto registerDto)
        {
            try
            {
                var result = await _userService.RegisterAsync(registerDto);
                if (result != null)
                {
                    return this.SuccessResult(result, "注册成功");
                }
                return this.FailResult("注册失败");
            }
            catch (InvalidOperationException ex)
            {
                return this.FailResult(ex.Message);
            }
            catch (Exception ex)
            {
                return this.ServerErrorResult($"注册失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取当前用户信息
        /// </summary>
        [HttpGet("profile")]
        [Authorize]
        public async Task<IActionResult> GetProfile()
        {
            try
            {
                var userIdClaim = User.FindFirst("UserId")?.Value;
                if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out Guid userId))
                {
                    return this.UnauthorizedResult("无效的用户信息");
                }

                var user = await _userService.GetUserByIdAsync(userId);
                if (user != null)
                {
                    return this.SuccessResult(user, "获取用户信息成功");
                }
                return this.NotFoundResult("用户不存在");
            }
            catch (Exception ex)
            {
                return this.ServerErrorResult($"获取用户信息失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取所有用户（分页）
        /// </summary>
        /// <summary>
        /// 获取用户列表（支持搜索和筛选）
        /// </summary>
        [HttpPost("list")]
        [Authorize]
        public async Task<IActionResult> GetUsers([FromBody] UserSearchDto searchDto)
        {
            try
            {
                // 设置默认分页参数
                if (searchDto.PageNumber <= 0) searchDto.PageNumber = 1;
                if (searchDto.PageSize <= 0) searchDto.PageSize = 10;
                
                var (users, totalCount) = await _userService.SearchUsersAsync(searchDto);
                return this.PagedResult(users, searchDto.PageNumber, searchDto.PageSize, totalCount, "获取用户列表成功");
            }
            catch (Exception ex)
            {
                return this.ServerErrorResult($"获取用户列表失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 根据ID获取用户
        /// </summary>
        [HttpGet("{id}")]
        [Authorize]
        public async Task<IActionResult> GetUserById(Guid id)
        {
            try
            {
                var user = await _userService.GetUserByIdAsync(id);
                if (user != null)
                {
                    return this.SuccessResult(user, "获取用户信息成功");
                }
                return this.NotFoundResult("用户不存在");
            }
            catch (Exception ex)
            {
                return this.ServerErrorResult($"获取用户信息失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新用户信息
        /// </summary>
        [HttpPut("{id}")]
        [Authorize]
        public async Task<IActionResult> UpdateUser(Guid id, [FromBody] UpdateUserDto updateUserDto)
        {
            try
            {
                // 手动验证必填字段
                if (string.IsNullOrWhiteSpace(updateUserDto.UserName))
                {
                    return this.FailResult("用户名不能为空");
                }
                
                if (string.IsNullOrWhiteSpace(updateUserDto.Phone))
                {
                    return this.FailResult("手机号不能为空");
                }
                
                // 验证邮箱格式（如果提供了邮箱）
                if (!string.IsNullOrWhiteSpace(updateUserDto.Email) && 
                    !System.Text.RegularExpressions.Regex.IsMatch(updateUserDto.Email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$"))
                {
                    return this.FailResult("邮箱格式不正确");
                }
                
                var result = await _userService.UpdateUserAsync(id, updateUserDto);
                if (result)
                {
                    return this.SuccessResult("更新用户信息成功");
                }
                return this.NotFoundResult("用户不存在");
            }
            catch (Exception ex)
            {
                return this.ServerErrorResult($"更新用户信息失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        [HttpDelete("{id}")]
        [Authorize]
        public async Task<IActionResult> DeleteUser(Guid id)
        {
            try
            {
                var result = await _userService.DeleteUserAsync(id);
                if (result)
                {
                    return this.SuccessResult("删除用户成功");
                }
                return this.NotFoundResult("用户不存在");
            }
            catch (Exception ex)
            {
                return this.ServerErrorResult($"删除用户失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        [HttpPost("change-password")]
        [Authorize]
        public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordDto changePasswordDto)
        {
            try
            {
                var userIdClaim = User.FindFirst("UserId")?.Value;
                if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out Guid userId))
                {
                    return this.UnauthorizedResult("无效的用户信息");
                }

                var result = await _userService.ChangePasswordAsync(userId, changePasswordDto);
                if (result)
                {
                    return this.SuccessResult("密码修改成功");
                }
                return this.FailResult("原密码错误或修改失败");
            }
            catch (Exception ex)
            {
                return this.ServerErrorResult($"修改密码失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 管理员重置用户密码
        /// </summary>
        [HttpPost("reset-password")]
        [Authorize]
        public async Task<IActionResult> ResetUserPassword([FromBody] ResetUserPasswordDto resetPasswordDto)
        {
            try
            {
                var result = await _userService.ResetUserPasswordAsync(resetPasswordDto.UserId, resetPasswordDto.NewPassword);
                if (result)
                {
                    return this.SuccessResult("用户密码重置成功");
                }
                return this.NotFoundResult("用户不存在");
            }
            catch (Exception ex)
            {
                return this.ServerErrorResult($"重置用户密码失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 刷新Token
        /// </summary>
        [HttpPost("refresh-token")]
        [Authorize]
        public async Task<IActionResult> RefreshToken()
        {
            try
            {
                var userIdClaim = User.FindFirst("UserId")?.Value;
                if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out Guid userId))
                {
                    return this.UnauthorizedResult("无效的用户信息");
                }

                var result = await _userService.RefreshTokenAsync(userId);
                if (result != null)
                {
                    return this.SuccessResult(result, "Token刷新成功");
                }
                return this.UnauthorizedResult("Token刷新失败");
            }
            catch (Exception ex)
            {
                return this.ServerErrorResult($"Token刷新失败: {ex.Message}");
            }
        }

        #region 用户状态管理

        /// <summary>
        /// 启用用户
        /// </summary>
        [HttpPost("{id}/enable")]
        [Authorize]
        public async Task<IActionResult> EnableUser(Guid id, [FromBody] UpdateUserStatusDto statusDto = null)
        {
            try
            {
                var result = await _userService.EnableUserAsync(id, statusDto?.Reason);
                if (result)
                {
                    return this.SuccessResult("用户启用成功");
                }
                return this.NotFoundResult("用户不存在");
            }
            catch (Exception ex)
            {
                return this.ServerErrorResult($"启用用户失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 禁用用户
        /// </summary>
        [HttpPost("{id}/disable")]
        [Authorize]
        public async Task<IActionResult> DisableUser(Guid id, [FromBody] UpdateUserStatusDto statusDto = null)
        {
            try
            {
                var result = await _userService.DisableUserAsync(id, statusDto?.Reason);
                if (result)
                {
                    return this.SuccessResult("用户禁用成功");
                }
                return this.NotFoundResult("用户不存在");
            }
            catch (Exception ex)
            {
                return this.ServerErrorResult($"禁用用户失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 锁定用户
        /// </summary>
        [HttpPost("{id}/lock")]
        [Authorize]
        public async Task<IActionResult> LockUser(Guid id, [FromBody] UpdateUserStatusDto statusDto = null)
        {
            try
            {
                var result = await _userService.LockUserAsync(id, statusDto?.Reason);
                if (result)
                {
                    return this.SuccessResult("用户锁定成功");
                }
                return this.NotFoundResult("用户不存在");
            }
            catch (Exception ex)
            {
                return this.ServerErrorResult($"锁定用户失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 解锁用户
        /// </summary>
        [HttpPost("{id}/unlock")]
        [Authorize]
        public async Task<IActionResult> UnlockUser(Guid id, [FromBody] UpdateUserStatusDto statusDto = null)
        {
            try
            {
                var result = await _userService.UnlockUserAsync(id, statusDto?.Reason);
                if (result)
                {
                    return this.SuccessResult("用户解锁成功");
                }
                return this.NotFoundResult("用户不存在");
            }
            catch (Exception ex)
            {
                return this.ServerErrorResult($"解锁用户失败: {ex.Message}");
            }
        }

        #endregion

        #region 搜索和筛选

        /// <summary>
        /// 搜索用户
        /// </summary>
        [HttpGet("search")]
        [Authorize]
        public async Task<IActionResult> SearchUsers([FromQuery] UserSearchDto searchDto)
        {
            try
            {
                var (users, totalCount) = await _userService.SearchUsersAsync(searchDto);
                return this.PagedResult(users, searchDto.PageNumber, searchDto.PageSize, totalCount, "搜索用户成功");
            }
            catch (Exception ex)
            {
                return this.ServerErrorResult($"搜索用户失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 按状态筛选用户
        /// </summary>
        [HttpGet("filter/status/{status}")]
        [Authorize]
        public async Task<IActionResult> GetUsersByStatus(int status, [FromQuery] int pageNumber = 1, [FromQuery] int pageSize = 10)
        {
            try
            {
                var users = await _userService.GetUsersByStatusAsync(status, pageNumber, pageSize);
                return this.SuccessResult(users, "获取用户列表成功");
            }
            catch (Exception ex)
            {
                return this.ServerErrorResult($"获取用户列表失败: {ex.Message}");
            }
        }

        #endregion

        #region 批量操作

        /// <summary>
        /// 批量启用用户
        /// </summary>
        [HttpPost("batch/enable")]
        [Authorize]
        public async Task<IActionResult> BatchEnableUsers([FromBody] BatchOperationDto batchDto)
        {
            try
            {
                var result = await _userService.BatchEnableUsersAsync(batchDto);
                if (result)
                {
                    return this.SuccessResult("批量启用用户成功");
                }
                return this.FailResult("批量启用用户失败");
            }
            catch (Exception ex)
            {
                return this.ServerErrorResult($"批量启用用户失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 批量禁用用户
        /// </summary>
        [HttpPost("batch/disable")]
        [Authorize]
        public async Task<IActionResult> BatchDisableUsers([FromBody] BatchOperationDto batchDto)
        {
            try
            {
                var result = await _userService.BatchDisableUsersAsync(batchDto);
                if (result)
                {
                    return this.SuccessResult("批量禁用用户成功");
                }
                return this.FailResult("批量禁用用户失败");
            }
            catch (Exception ex)
            {
                return this.ServerErrorResult($"批量禁用用户失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 批量删除用户
        /// </summary>
        [HttpPost("batch/delete")]
        [Authorize]
        public async Task<IActionResult> BatchDeleteUsers([FromBody] BatchOperationDto batchDto)
        {
            try
            {
                var result = await _userService.BatchDeleteUsersAsync(batchDto);
                if (result)
                {
                    return this.SuccessResult("批量删除用户成功");
                }
                return this.FailResult("批量删除用户失败");
            }
            catch (Exception ex)
            {
                return this.ServerErrorResult($"批量删除用户失败: {ex.Message}");
            }
        }

        #endregion
        /// <summary>
        /// 管理员创建用户
        /// </summary>
        [HttpPost("create")]
        [Authorize] // 需要管理员权限
        public async Task<IActionResult> CreateUser([FromBody] CreateUserDto createUserDto)
        {
            try
            {
                var result = await _userService.CreateUserAsync(createUserDto);
                if (result != null)
                {
                    return this.SuccessResult(result, "创建用户成功");
                }
                return this.FailResult("创建用户失败");
            }
            catch (InvalidOperationException ex)
            {
                // 业务逻辑异常，返回具体错误信息
                return this.FailResult(ex.Message);
            }
            catch (Exception ex)
            {
                // 其他系统异常，返回具体错误信息但可以记录日志
                return this.FailResult(ex.Message);
            }
        }
        #region 用户角色管理

        /// <summary>
        /// 为用户分配角色
        /// </summary>
        [HttpPost("assign-roles")]
        [Authorize]
        public async Task<IActionResult> AssignRoles([FromBody] AssignRolesDto assignRolesDto)
        {
            try
            {
                await _userService.AssignRolesAsync(assignRolesDto.UserId, assignRolesDto.RoleIds);
                return this.SuccessResult("角色分配成功");
            }
            catch (Exception ex)
            {
                return this.ServerErrorResult($"角色分配失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取用户的角色信息
        /// </summary>
        [HttpGet("roles/{userId}")]
        [Authorize]
        public async Task<IActionResult> GetUserRoles(Guid userId)
        {
            try
            {
                var userWithRoles = await _userService.GetUserWithRolesAsync(userId);
                if (userWithRoles == null)
                {
                    return this.NotFoundResult("用户不存在");
                }
                return this.SuccessResult(userWithRoles, "获取用户角色成功");
            }
            catch (Exception ex)
            {
                return this.ServerErrorResult($"获取用户角色失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 移除用户的所有角色
        /// </summary>
        [HttpDelete("{id}/roles")]
        [Authorize]
        public async Task<IActionResult> RemoveUserRoles(Guid id)
        {
            try
            {
                await _userService.AssignRolesAsync(id, new List<Guid>());
                return this.SuccessResult("用户角色清除成功");
            }
            catch (Exception ex)
            {
                return this.ServerErrorResult($"清除用户角色失败: {ex.Message}");
            }
        }

        #endregion

        #region 服务发现相关方法

        /// <summary>
        /// 获取用户的产品信息（通过服务发现调用Product服务）
        /// </summary>
        [HttpGet("{userId}/products")]
        [Authorize]
        public async Task<IActionResult> GetUserProducts(Guid userId)
        {
            try
            {
                // 首先验证用户是否存在
                var user = await _userService.GetUserByIdAsync(userId);
                if (user == null)
                {
                    return this.NotFoundResult("用户不存在");
                }

                // 通过服务发现获取产品服务的URL
                var productServiceUrl = await _serviceDiscovery.GetServiceUrlAsync("hao-product-api");
                
                if (string.IsNullOrEmpty(productServiceUrl))
                {
                    _logger.LogWarning("产品服务不可用");
                    return this.ServerErrorResult("产品服务不可用");
                }

                // 调用产品服务获取用户的产品信息
                var response = await _httpClient.GetAsync($"{productServiceUrl}/api/product/user/{userId}");
                
                if (response.IsSuccessStatusCode)
                {
                    var productInfo = await response.Content.ReadAsStringAsync();
                    _logger.LogInformation($"成功获取用户产品信息: {userId}");
                    return this.SuccessResult(JsonSerializer.Deserialize<object>(productInfo), "获取用户产品信息成功");
                }
                
                _logger.LogWarning($"调用产品服务失败: {response.StatusCode}");
                return this.ServerErrorResult("调用产品服务失败");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取用户产品信息时发生错误: {userId}");
                return this.ServerErrorResult($"获取用户产品信息失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 测试产品服务连接
        /// </summary>
        [HttpGet("test-product-service")]
        //[Authorize]
        public async Task<IActionResult> TestProductService()
        {
            try
            {
                var productServiceUrl = await _serviceDiscovery.GetServiceUrlAsync("product-api");
                
                if (string.IsNullOrEmpty(productServiceUrl))
                {
                    return this.ServerErrorResult("产品服务不可用");
                }

                var response = await _httpClient.GetAsync($"{productServiceUrl}/api/product/test");
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    return this.SuccessResult(new 
                    {
                        productServiceUrl,
                        response = JsonSerializer.Deserialize<object>(result)
                    }, "产品服务连接正常");
                }
                
                return this.ServerErrorResult($"产品服务响应异常: {response.StatusCode}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "测试产品服务连接时发生错误");
                return this.ServerErrorResult($"测试产品服务失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取所有可用的服务实例
        /// </summary>
        [HttpGet("services")]
        [Authorize]
        public async Task<IActionResult> GetAvailableServices()
        {
            try
            {
                var userServiceInstances = await _serviceDiscovery.GetHealthyServiceInstancesAsync("hao-user-api");
                var productServiceInstances = await _serviceDiscovery.GetHealthyServiceInstancesAsync("hao-product-api");
                
                return this.SuccessResult(new 
                {
                    services = new
                    {
                        userService = userServiceInstances,
                        productService = productServiceInstances
                    }
                }, "获取服务实例成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取服务实例时发生错误");
                return this.ServerErrorResult($"获取服务实例失败: {ex.Message}");
            }
        }

        #endregion

        #region 用户留言相关接口

        /// <summary>
        /// 获取用户的留言列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="page">页码</param>
        /// <param name="pageSize">每页数量</param>
        /// <returns>用户留言列表</returns>
        /// <response code="200">获取成功</response>
        /// <response code="401">未授权</response>
        /// <response code="500">服务器内部错误</response>
        [HttpGet("{userId}/comments")]
        [Authorize]
        public async Task<IActionResult> GetUserComments(
            Guid userId,
            [FromQuery] int page = 1,
            [FromQuery] int pageSize = 20)
        {
            try
            {
                // 验证用户权限（只能查看自己的留言或管理员可查看所有）
                var currentUserIdClaim = User.FindFirst("UserId")?.Value;
                if (!Guid.TryParse(currentUserIdClaim, out var currentUserId))
                {
                    return this.UnauthorizedResult("用户身份验证失败");
                }

                if (currentUserId != userId && !User.IsInRole("Admin"))
                {
                    return this.ForbiddenResult("无权限查看其他用户的留言");
                }

                // 通过服务发现调用商品服务获取用户留言
                var productServiceUrl = await _serviceDiscovery.GetServiceUrlAsync("hao-product-api");
                if (string.IsNullOrEmpty(productServiceUrl))
                {
                    return this.ServerErrorResult("商品服务不可用");
                }

                var response = await _httpClient.GetAsync(
                    $"{productServiceUrl}/api/product/user/{userId}/comments?page={page}&pageSize={pageSize}");

                if (response.IsSuccessStatusCode)
                {
                    var commentsInfo = await response.Content.ReadAsStringAsync();
                    _logger.LogInformation("成功获取用户留言信息: {UserId}", userId);
                    return this.SuccessResult(
                        JsonSerializer.Deserialize<object>(commentsInfo),
                        "获取用户留言成功");
                }

                _logger.LogWarning("调用商品服务获取用户留言失败: {StatusCode}", response.StatusCode);
                return this.ServerErrorResult("获取用户留言失败");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户留言时发生错误: {UserId}", userId);
                return this.ServerErrorResult($"获取用户留言失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取用户的留言统计信息
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>留言统计</returns>
        /// <response code="200">获取成功</response>
        /// <response code="401">未授权</response>
        /// <response code="500">服务器内部错误</response>
        [HttpGet("{userId}/comments/stats")]
        [Authorize]
        public async Task<IActionResult> GetUserCommentStats(Guid userId)
        {
            try
            {
                // 验证用户权限
                var currentUserIdClaim = User.FindFirst("UserId")?.Value;
                if (!Guid.TryParse(currentUserIdClaim, out var currentUserId))
                {
                    return this.UnauthorizedResult("用户身份验证失败");
                }

                if (currentUserId != userId && !User.IsInRole("Admin"))
                {
                    return this.ForbiddenResult("无权限查看其他用户的留言统计");
                }

                // 通过服务发现调用商品服务获取用户留言统计
                var productServiceUrl = await _serviceDiscovery.GetServiceUrlAsync("hao-product-api");
                if (string.IsNullOrEmpty(productServiceUrl))
                {
                    return this.ServerErrorResult("商品服务不可用");
                }

                var response = await _httpClient.GetAsync(
                    $"{productServiceUrl}/api/product/user/{userId}/comments/stats");

                if (response.IsSuccessStatusCode)
                {
                    var statsInfo = await response.Content.ReadAsStringAsync();
                    _logger.LogInformation("成功获取用户留言统计: {UserId}", userId);
                    return this.SuccessResult(
                        JsonSerializer.Deserialize<object>(statsInfo),
                        "获取用户留言统计成功");
                }

                _logger.LogWarning("调用商品服务获取用户留言统计失败: {StatusCode}", response.StatusCode);
                return this.ServerErrorResult("获取用户留言统计失败");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户留言统计时发生错误: {UserId}", userId);
                return this.ServerErrorResult($"获取用户留言统计失败: {ex.Message}");
            }
        }

        #endregion

        /// <summary>
        /// 测试调用订单服务 - 获取用户订单
        /// </summary>
        [HttpGet("test/orders/{userId}")]
        public async Task<IActionResult> TestGetUserOrders(Guid userId)
        {
            try
            {
                var orderServiceUrl = await _serviceDiscovery.GetServiceUrlAsync("hao-order-api");
                
                if (string.IsNullOrEmpty(orderServiceUrl))
                {
                    return this.ServerErrorResult("订单服务不可用");
                }

                var response = await _httpClient.GetAsync($"{orderServiceUrl}/api/order/buyer/{userId}");
                
                if (response.IsSuccessStatusCode)
                {
                    var orderInfo = await response.Content.ReadAsStringAsync();
                    _logger.LogInformation("成功获取用户订单信息: {UserId}", userId);
                    return this.SuccessResult(new 
                    {
                        serviceUrl = orderServiceUrl,
                        orders = JsonSerializer.Deserialize<object>(orderInfo)
                    }, "获取用户订单成功");
                }
                
                _logger.LogWarning($"调用订单服务失败: {response.StatusCode}");
                return this.ServerErrorResult("调用订单服务失败");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户订单时发生错误: {UserId}", userId);
                return this.ServerErrorResult($"获取用户订单失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 综合测试 - 模拟用户注册时的服务调用
        /// </summary>
        [HttpPost("test/registration-simulation")]
        public async Task<IActionResult> TestUserRegistrationSimulation([FromBody] TestUserDto testUser)
        {
            try
            {
                var results = new List<object>();

                // 1. 检查商品服务是否可用
                try
                {
                    var productServiceUrl = await _serviceDiscovery.GetServiceUrlAsync("hao-product-api");
                    if (!string.IsNullOrEmpty(productServiceUrl))
                    {
                        var productResponse = await _httpClient.GetAsync($"{productServiceUrl}/api/product/test/services");
                        if (productResponse.IsSuccessStatusCode)
                        {
                            results.Add(new { service = "product", status = "available" });
                        }
                        else
                        {
                            results.Add(new { service = "product", status = "error", message = $"HTTP {productResponse.StatusCode}" });
                        }
                    }
                    else
                    {
                        results.Add(new { service = "product", status = "unavailable" });
                    }
                }
                catch (Exception ex)
                {
                    results.Add(new { service = "product", status = "error", message = ex.Message });
                }

                // 2. 检查订单服务是否可用
                try
                {
                    var orderServiceUrl = await _serviceDiscovery.GetServiceUrlAsync("hao-order-api");
                    if (!string.IsNullOrEmpty(orderServiceUrl))
                    {
                        var orderResponse = await _httpClient.GetAsync($"{orderServiceUrl}/api/order/test/services");
                        if (orderResponse.IsSuccessStatusCode)
                        {
                            results.Add(new { service = "order", status = "available" });
                        }
                        else
                        {
                            results.Add(new { service = "order", status = "error", message = $"HTTP {orderResponse.StatusCode}" });
                        }
                    }
                    else
                    {
                        results.Add(new { service = "order", status = "unavailable" });
                    }
                }
                catch (Exception ex)
                {
                    results.Add(new { service = "order", status = "error", message = ex.Message });
                }

                return this.SuccessResult(new 
                {
                    testUser = testUser,
                    serviceCallResults = results,
                    timestamp = DateTime.Now
                }, "用户注册模拟测试完成");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "用户注册模拟测试失败");
                return this.ServerErrorResult($"用户注册模拟测试失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 调试：检查 Consul 连接状态
        /// </summary>
        [HttpGet("debug/consul-status")]
        public async Task<IActionResult> GetConsulStatus()
        {
            try
            {
                // 检查当前服务是否能获取到自己
                var userServiceInstances = await _serviceDiscovery.GetHealthyServiceInstancesAsync("hao-user-api");
                var productServiceInstances = await _serviceDiscovery.GetHealthyServiceInstancesAsync("hao-product-api");
                var orderServiceInstances = await _serviceDiscovery.GetHealthyServiceInstancesAsync("hao-order-api");
                
                return this.SuccessResult(new 
                {
                    consulConnection = "Connected",
                    userServiceCount = userServiceInstances?.Count() ?? 0,
                    productServiceCount = productServiceInstances?.Count() ?? 0,
                    orderServiceCount = orderServiceInstances?.Count() ?? 0,
                    userServices = userServiceInstances,
                    productServices = productServiceInstances,
                    orderServices = orderServiceInstances,
                    timestamp = DateTime.Now
                }, "Consul 状态检查完成");
            }
            catch (Exception ex)
            {
                return this.ServerErrorResult($"Consul 连接失败: {ex.Message}");
            }
        }
    }

    /// <summary>
    /// 测试用户DTO
    /// </summary>
    public class TestUserDto
    {
        public string UserName { get; set; } = string.Empty;
        public string Email { get; set; } = string.Empty;
        public string Phone { get; set; } = string.Empty;
        public string Avatar { get; set; } = string.Empty;
    }
}